package com.snoopy.gas1.controller;

import com.snoopy.gas1.entity.Register;
import com.snoopy.gas1.mapper.RegisterMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    private final RegisterMapper registerMapper;

    public LoginController(RegisterMapper registerMapper) {
        this.registerMapper = registerMapper;
    }

    @RequestMapping("/login")
    public String loginPage(Model model) {
        return "index"; // 返回登录页面
    }

    @PostMapping("/user/login")
    public String login(HttpSession session, Model model,
                        @RequestParam("username") String username,
                        @RequestParam("password") String password) {

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            model.addAttribute("msg", "用户名和密码不能为空");
            return "index";
        }

        // 从数据库查询用户信息
        Register register = registerMapper.findByEmployeeName(username);

        if (register != null && password.equals(register.getPassword())) {
            session.setAttribute("loginUser", username);
            return "redirect:/login.html"; // 登录成功跳转到login.html
        } else {
            model.addAttribute("msg", "用户名或密码错误");
            return "index"; // 登录失败返回index.html并显示错误信息
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser"); // 清除session中的用户信息
        return "redirect:/index.html"; // 重定向到登录页面
    }
}